package com.cartrentalsystem.controller;


import com.cartrentalsystem.context.BaseContext;
import com.cartrentalsystem.domain.po.User;
import com.cartrentalsystem.domain.vo.Result;
import com.cartrentalsystem.domain.vo.UserVo;
import com.cartrentalsystem.service.IUserService;
import com.cartrentalsystem.utils.AliyunUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LHD
 * @since 2025-06-12
 */
@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    private final RedisTemplate redisTemplate;

    @GetMapping()
    public Result<UserVo> getUser() {
        // 这里获取当前用户要用redis缓存，并存在LocalThread中
        Long userId = BaseContext.getCurrentId();
        UserVo userVo = (UserVo)redisTemplate.opsForValue().get("userId:" + userId);
//        User user = userService.getById(userId);
        return userVo != null ? Result.success(userVo) : Result.fail("用户不存在");
    }

    @PutMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        Long userId = BaseContext.getCurrentId();
        user.setId(Math.toIntExact(userId));
        log.info("修改用户信息：{}", user);
        boolean update = userService.updateUser(user);
        return update ? Result.success("更新成功") : Result.fail("更新失败");
    }

    @PostMapping("/upload")
    public Result upload(@Param("file") MultipartFile file) throws Exception {
        return userService.uploadImage(file);
    }

    @PutMapping("/updatePassword")
    public Result<String> updatePassword(@Param("username") String username, @Param("oldPassword") String oldPassword, @Param("newPassword") String newPassword) {
        Long userId = BaseContext.getCurrentId();
        log.info("修改用户密码：{},{},{},{}", userId,username,oldPassword,newPassword);
        boolean update = userService.updatePassword(userId, username, oldPassword,newPassword);
        return update ? Result.success("更新成功") : Result.fail("原密码错误");
    }

}
